package edu.del.teamknowledgebase.web.controller;

import cn.hutool.core.util.StrUtil;
import edu.del.teamknowledgebase.common.exception.BusinessException;
import edu.del.teamknowledgebase.common.result.Result;
import edu.del.teamknowledgebase.dto.*;
import edu.del.teamknowledgebase.service.code.CodeService;
import edu.del.teamknowledgebase.vo.CaptchaVO;
import edu.del.teamknowledgebase.service.auth.AuthService;
import edu.del.teamknowledgebase.service.auth.CaptchaService;
import edu.del.teamknowledgebase.service.sms.SmsService;
import edu.del.teamknowledgebase.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;


@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final CaptchaService captchaService;
    private final SmsService smsService;
    private final AuthService authService;
    private final CodeService codeService;


    /**
     * 获取图片验证码
     */
    @GetMapping("/captcha")
    public Result<CaptchaVO> getCaptcha() {
        CaptchaVO captchaVO = captchaService.generateCaptcha();
        return Result.success(captchaVO);
    }

    /**
     * 发送验证码
     */
    @PostMapping("/send-code")
    public Result<?> sendCode(@RequestBody Map<String, String> params) {
        String receiver = params.get("receiver");
        String type = params.get("type");
        String scene = params.get("scene");

        codeService.sendVerificationCode(receiver, type, scene);
        return Result.success();
    }

    /**
     * 验证验证码
     */
    @PostMapping("/verify-code")
    public Result<?> verifyCode(@RequestParam String receiver, @RequestParam String code) {
        if (StrUtil.isBlank(receiver) || StrUtil.isBlank(code)) {
            return Result.error("参数不能为空");
        }
        return smsService.verifyCode(receiver, code) ? Result.success() : Result.error("验证码错误");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        try {
            UserVO user = authService.login(loginRequest, request);
            return Result.success(user);
        } catch (RuntimeException e) {
            log.error("登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        try {
            authService.logout(request);
            return Result.success("登出成功");
        } catch (RuntimeException e) {
            log.error("登出失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody RegisterRequest registerRequest, HttpServletRequest request) {
        try {
            UserVO user = authService.register(registerRequest, request);
            return Result.build().success(true).code(200).message("注册成功").data(user);
        } catch (BusinessException e) {
            log.error("注册失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户
     */
    @PostMapping("/current-user")
    public Result<UserVO> getCurrentUser(HttpServletRequest request) {
        try {
            UserVO currentUser = authService.getCurrentUser(request);
            return Result.success(currentUser);
        } catch (BusinessException e) {
            log.error("获取当前用户失败: {}", e.getMessage());
            // 未登录 Session 过期返回 401
            if (e.getMessage().contains("未登录") || e.getMessage().contains("过期")) {
                return Result.fail(401, e.getMessage());
            }
            return Result.error(e.getMessage());
        }
    }

    /**
     * 判断用户是否登录
     */
    @PostMapping("/is-logged-in")
    public Result<?> isLoggedIn(HttpServletRequest request) {
        try {
            boolean loggedIn = authService.isLoggedIn(request);
            return Result.build().success(loggedIn).code(200).message(loggedIn ? "已登录" : "未登录");
        } catch (BusinessException e) {
            log.error("检查登录状态失败: {}", e.getMessage());
            // 未登录或session过期的情况，返回false表示未登录
            return Result.build().success(false).code(401).message(e.getMessage());
        }
    }

    /**
     * 获取敏感信息
     */
    @PostMapping("/sensitive-info")
    public Result<UserVO> getSensitiveInfo(@RequestBody Map<String, String> params, HttpServletRequest request) {
        try {
            String password = params.get("password");
            UserVO user = authService.getSensitiveInfo(request, password);
            return Result.success(user);
        } catch (BusinessException e) {
            log.error("获取敏感信息失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/upload-avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        try {
            String avatarPath = authService.uploadAvatar(file, request);
            return Result.success(avatarPath);
        } catch (BusinessException e) {
            log.error("上传头像失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改用户名
     */
    @PostMapping("/update-username")
    public Result<UserVO> updateUsername(@RequestBody Map<String, String> params, HttpServletRequest request) {
       try {
           String newUsername = params.get("username");
           UserVO userVO = authService.updateUsername(newUsername, request);
           return Result.success(userVO);
       } catch (BusinessException e) {
           log.error("修改用户名失败: {}", e.getMessage());
           return Result.error(e.getMessage());
       }
    }

    /**
     * 修改手机号
     */
    @PostMapping("rebind-phone")
    public Result<UserVO> rebindPhone(@RequestBody RebindPhoneRequest params, HttpServletRequest request) {
      try {
          String newPhone = params.getNewPhone();
          String code = params.getCode();
          UserVO userVO = authService.rebindPhone(newPhone, code, request);
          return Result.success(userVO);
      } catch (BusinessException e) {
          log.error("修改手机号失败: {}", e.getMessage());
          return Result.error(e.getMessage());
      }
    }

    /**
     * 修改邮箱
     */
    @PostMapping("rebind-email")
    public Result<UserVO> rebindEmail(@RequestBody RebindEmailRequest params, HttpServletRequest request) {
        try {
            String newEmail = params.getNewEmail();
            String code = params.getCode();
            UserVO userVO = authService.rebindEmail(newEmail, code, request);
            return Result.success(userVO);
        } catch (BusinessException e) {
            log.error("修改邮箱失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
